/* 
	商品分类管理模块 - categories
 */


/* ------------------------------------------------------------------------------------
	模块导入
------------------------------------------------------------------------------------ */
// 第三方模块 - express
const express = require('express')
/* ------------------------------------------------------------------------------------
	常量、变量、方法
------------------------------------------------------------------------------------ */
// 新建路由
const categoriesRouter = express.Router()
/* ------------------------------------------------------------------------------------
	路由配置
------------------------------------------------------------------------------------ */

/* 
|字段|类型|默认值|注释|主键|
|:----|:-------|:---|---|------|---|
|category_id|int(10) unsigned|	|PRI|分类主键id|
|category_name|varchar(30)|	||分类名|
 */

/* ------------------------------------------------------------------------------------
	GET
------------------------------------------------------------------------------------ */

// 根据id获取分类
categoriesRouter.get('/getById', async (req, res) => res.getById('category', 'category_id'))

// 获取分类
categoriesRouter.get('/get', async (req, res) => {
	console.log('获取分类')
	// 参数
	const category_name = req.query.category_name ? req.query.category_name : ''
	const pagenum = req.query.pagenum ? req.query.pagenum : 1
	const pagesize = req.query.pagesize ? req.query.pagesize : 10

	// 基础 sql 语句
	let sql = `SELECT * FROM category`

	// 无查询条件，匹配全部
	if (category_name !== '') sql += ` WHERE category_name LIKE '%${category_name}%'`

	// 发送 sql
	const pageindex = ( pagenum - 1 ) * pagesize
	const categories = await res.execSql(sql + ` LIMIT ${pageindex},${pagesize}`)

	// 总条数
	const {
		total
	} = (await res.execSql(`SELECT COUNT(category_id) AS total FROM category`))[0]

	// 总页数
	const totalPage = Math.ceil(total / pagesize)

	res.sendResult({
		categories,
		total,
		pagenum,
		totalPage
	}, 200, '获取成功')
})

/* ------------------------------------------------------------------------------------
	POST
------------------------------------------------------------------------------------ */

// 添加分类
categoriesRouter.post('/add', (req, res) => {
	console.log('添加分类')
	// 参数
	const {
		category_name
	} = req.body
	if (!category_name) return res.sendResult(null, 405, '请提供分类名')

	res.execSql(
		`INSERT INTO category SET category_name = '${category_name}')`
	)
	res.sendResult(null, 200, '添加成功')
})

/* ------------------------------------------------------------------------------------
	导出路由
------------------------------------------------------------------------------------ */
module.exports = categoriesRouter
